<?php
/**
 * Copyright (c) 2021-2222   All rights reserved.
 *
 * 创建时间：2021-12-11 00:14
 *
 * 项目：levs  -  $  - ${FILE_NAME}
 *
 * 作者：liwei
 */

//!defined('INLEV') && exit('Access Denied LEV');


namespace modules\qq\widgets\qzone;

use Lev;
use lev\helpers\curlHelper;
use modules\qq\helpers\cookieHelper;
use modules\qq\helpers\qqLoginHelper;

class BaseQzones
{

    public static $gtks = '';

    //QQ空间GTK算法
    public static function qzone_gtk($qq){
        if (!isset(static::$gtks[$qq])) {
            $str = cookieHelper::cookieArrv($qq, 'skey');
            $hash = 5381;
            $len = strlen($str);
            for ($i = 0; $i < $len; $i++) {
                $h = ($hash << 5) + ord($str[$i]);
                $hash += $h;
            }
            static::$gtks[$qq] = $hash & 0x7fffffff;
        }
        return static::$gtks[$qq];
    }

    public static function jsonFormatArr($ret) {
        $ret = substr(explode(');', strstr($ret, 'back('))[0], 5);
        return json_decode(trim($ret), true);
    }

    /**
     * @param $ret
     * @return array
     */
    public static function responseMsg($ret) {
        $arr = static::jsonFormatArr($ret);
//        if (Lev::$app['isAdmin']) {
//            print_r([$arr,$ret]);exit;
//        }

        if (!empty($arr['code'])) {
            $status = -1;
        }elseif ((!empty($arr['message']) && strpos($arr['message'], '成功') !==false)) {
            $status = 2;
        }else {
            $status = 1;
        }

        $message = empty($arr['message']) ? $status >0 ? '操作成功': '抓取失败' : $arr['message'];
        return Lev::responseMsg($status, $message, [$arr]);
    }

    //统一发送空间请求函数
    public static function getInfos($qq, $param, $gtk = true, $debug = false) {
        $param['cookiefile'] = qqLoginHelper::createCK($qq);

        if ($gtk) $param['url'] .= static::qzone_gtk($qq);;

        //if ($param['post'] && !$post) $param['post'] = http_build_query($param['post']);

//        $param['httpheader'] = ['Host: h5.qzone.qq.com
//User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0
//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
//Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
//Accept-Encoding: gzip, deflate, br
//Content-Type: application/x-www-form-urlencoded
//Content-Length: 440
//Origin: https://user.qzone.qq.com
//Connection: keep-alive
//Upgrade-Insecure-Requests: 1
//Sec-Fetch-Dest: iframe
//Sec-Fetch-Mode: navigate
//Sec-Fetch-Site: same-site
//TE: trailers'];

        $datas = curlHelper::doCurl($param);


        if ($debug) {
            print_r($param);print_r($datas);
        }
        return $datas;
    }

}